package com.freesky.quartz.task;

import com.freesky.biz.icbc.domain.TIntegralExchange;
import com.freesky.biz.icbc.service.IIntegralPartnerService;
import com.freesky.common.core.redis.RedisCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * 积分合伙人任务处理
 */
@Component("integralPartnerTask")
public class IntegralPartnerTask {
    private static final Logger logger = LoggerFactory.getLogger(IntegralPartnerTask.class);

    @Autowired
    private IIntegralPartnerService integralPartnerService;

    @Autowired
    private RedisCache redisCache;

    private String INTEGRAL_PARTNER_KEY = "INTEGRAL:PARTNER:LAST";

    private static final long INTERVAL = 120 * 1000 * 60;       //每隔2小时查询一次性
    private long lastAlarmTime = 0;

    public void taskProcess() {
        logger.info("IntegralPartnerTask task start");
        List<TIntegralExchange>  integralExchangeList = integralPartnerService.findPointList();
        for(TIntegralExchange integralExchange : integralExchangeList){
            integralPartnerService.processIntegralExchange(integralExchange);
        }
        //每二个小时更新一次
        if(canAllow()) {
            integralPartnerService.updatePartnerUserTotalAmt();
        }
    }

    private boolean canAllow() {
        Long stockMonitorTime = (Long)redisCache.getCacheObject(INTEGRAL_PARTNER_KEY);

        if(stockMonitorTime!=null){
            lastAlarmTime = stockMonitorTime.longValue();
        }

        long now = System.currentTimeMillis();
        if (now - lastAlarmTime >= INTERVAL) {
            lastAlarmTime = now;
            redisCache.setCacheObject(INTEGRAL_PARTNER_KEY,lastAlarmTime);
            return true;
        } else {
            return false;
        }
    }
}
